var api = require("../../../../api.js"),
  QQMapWX = require("../../../../qqmap-wx.js"),
  app = getApp();
Page({
  data: {
    panel: 0,
    carryIndex: 0,
    weight: 1,
    worth: 10,
    wareText: '',
    authStatus: true,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    iphoneModule: false,
    currentScrollIcon: 1,
  },
  onReady: function(){
    let systemInfo = wx.getSystemInfoSync();
    let modelStatus = systemInfo.model.split(" ")[0];
    let systemVersion = systemInfo.system.split(".")[0].split(" ")[1];
    if (modelStatus == "iPhone") {
      this.setData({
        iphoneModule: true,
        panel: 0
      })
    }
    // 切换下标状态
    scrollIconGroupAction({ page: this });
    // 获取地图
    this.getLocaltion();
  },
  switchPanel: function (e) {
    var that = this;
    var panelVal = e.currentTarget.dataset.panel;
    that.setData({
      panel: panelVal
    });
   
  },
  changeInputData: function (e) {
    var that = this;
    var inputName = e.currentTarget.dataset.name;
    var inputVlaue = e.detail.value;
    if (inputName == "wareText") {
      that.setData({
        wareText: inputVlaue
      });
    }
  },
  checkCarryItem: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    that.setData({
      carryIndex: index
    })
  },
  pickerSelector: function (e) {
    var that = this;
    var pickerType = e.currentTarget.dataset.type;
    var val = e.detail.value;
    if (pickerType == 'weight') {
      that.setData({
        weight: that.data.weightArr[val]
      });
    }
    if (pickerType == 'worth') {
      that.setData({
        worth: that.data.worthArr[val]
      });
    }
  },
  /**
   * 跳转功能页面
   */
  navToPage: function (e) {
    var that = this;
    var _pageType = e.currentTarget.dataset.pagetype;
    var _url = this.findPageByPageType(_pageType) + "?id=" + e.currentTarget.dataset.id + '&cid=' + e.currentTarget.id;
    if (!that.isLogin()) {
      that.gotoLogin();
    } else {
      wx.navigateTo({
        url: _url,
      })
    }
  },
  findPageByPageType: function (pageType){
    let _this =  this;
    let _pageUrlArr = _this.data.pageUrlArr;
    let _pageUrl = null;
    _pageUrlArr.forEach(function(item,index){
      if (pageType == item.id){
        _pageUrl = item.pageUrl;
      }
    });
    return _pageUrl;
  },
  /**
   * 跳转用户页面
   */
  navToUserPage: function (e) {
    var that = this;
    if (!that.isLogin()) {
      that.gotoLogin();
    } else {
      wx.navigateTo({
        url: "/sd_liferuning/pages/constmer/user/index",
      })
    }
  },

  //自定义底部跳转
  naveClick: function (t) {
    app.navigatorClick(t, this);
  },
  // 保存搜索内容
  setSearch: function (e) {
    this.setData({
      search: e.detail.value
    })
  },
  //搜索方法
  searchAct: function () {
    let _this = this;
    let searchLinkedUrl = _this.data.pageConfig.mainConfig.searchConfig.searchLinkedUrl;
    let search = _this.data.search ? _this.data.search : '';
    wx.navigateTo({
      url: searchLinkedUrl + '?wareText=' + search,
    })
  },
  onShow: function () {
    var that=this;
    app.request({
      url: api.member.viptime,
      data: {
        uid: wx.getStorageSync('uid'),
        bid: wx.getStorageSync('bid')
      },
      success: function (e) {
        // 积分扣除成功
        //console.log('eeeeee', e)
        wx.setStorageSync('huiyuan',e.data)
      }
    })
    app.request({
      url: api.message.list,
      data:{
        bid: wx.getStorageSync('bid'),
      },
      success:function(res){
        that.setData({
          notice:res.data
        })
      }
    })
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(res);
        var demo = new QQMapWX({
          key: 'EKJBZ-72L3P-FHXDL-VSLEP-JEAGJ-JTFSD' // 必填
        });
        demo.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (loc) {
              that.setData({
                locationNow: loc.result.address_component.district
              })
          }
        });
        app.request({
          url:api.user.getmap,
         data:{
           latitude: res.latitude,
           longitude:res.longitude,
           bid:wx.getStorageSync('bid')
         },
          success:function(e){
            console.log(e);
            if(e.code==1){
             that.setData({
               markers: e.data
             })
            }
          }
        })
      },
      fail: function () {
        wx.showModal({
          title: '温馨提醒',
          content: '需要获取您的地理位置才能使用小程序',
          showCancel: false,
          confirmText: '获取位置',
          success: function (res) {
            if (res.confirm) {
              getAuthor();
            }
          }, fail: (res) => {
            getAuthor();
          }
        })
      }
    })
  },
  
  onLoad: function (options) {
  
    if (options.scene){
      wx.setStorageSync('referee', options.scene);
    }
    var that = this;
    // var o = wx.getStorageSync('page_index');
    // console.log("---",o)
    // o ? that.setData(o) : wx.showLoading({
    //   title: '请稍后',
    // });

    app.request({
      url: api.default.store,
      success: function (t) {
        wx.setStorageSync('bid', t.bid.bid)
        that.loadpage();  
      },
    }); 
    that.setData({
      icons: wx.getStorageSync('site') + '/addons/sd_liferuning/tp/public/uploads/background',
    })
    app.pageOnLoad(that);
    
  },

  loadpage() {
    let _this = this;
    if (wx.getStorageSync('index')) {
      let pageConfig = wx.getStorageSync('index');
      // 设置标题
      wx.setNavigationBarTitle({
        title: pageConfig.titleConfig.pageTitle
      })
      // 设置颜色
      wx.setNavigationBarColor({
        frontColor: pageConfig.titleConfig.fontColor.toLocaleLowerCase(),
        backgroundColor: pageConfig.titleConfig.navigationBgColor,
        animation: {
          duration: 400,
          timingFunc: 'easeIn'
        }
      })

      // 设置数据
      _this.setData({
        pageConfig: pageConfig
      });
    }
    app.request({
      method: 'POST',
      url: api.default.indexGetPageConfig,
      data: {
        bid: wx.getStorageSync('bid')
      },
      success: function (data) {
        let status = data.status;
        let pageConfig = JSON.parse(data.diy);
        wx.setStorageSync('index', pageConfig);
        if (status) {
          // 设置标题
          wx.setNavigationBarTitle({
            title: pageConfig.titleConfig.pageTitle
          })
          // 设置颜色
          wx.setNavigationBarColor({
            frontColor: pageConfig.titleConfig.fontColor.toLocaleLowerCase(),
            backgroundColor: pageConfig.titleConfig.navigationBgColor,
            animation: {
              duration: 400,
              timingFunc: 'easeIn'
            }
          })

          // 设置数据
          _this.setData({
            pageConfig: pageConfig
          });
        }
      }
    });
    wx.getStorage({
      key: 'uid',
      success: function (res) {
        _this.setData({
          authStatus: true
        });
      },
      fail: function (res) {
        app.request({
          url: api.default.homeimg,
          data: {
            bid: wx.getStorageSync('bid')
          },
          success: function (e) {
            if (e.code == 1) {
              _this.setData({
                homeimg: e.src
              })
            }
          }
        });
        _this.setData({
          authStatus: false
        });
      }
    })
  },
  onShareAppMessage: function (e) {
    
    let imgUrl = this.data.shareImgUrl;
    return {
      title: '您的好友' + wx.getStorageSync('nickname') + '邀您加入跑腿',
      imageUrl: imgUrl,
      desc: '发现一个很好的应用',
      path: 'sd_liferuning/pages/constmer/index/index',
      success: function (e) {
       
        if (e) {
          app.request({
            url: api.Coupon.list,
            data: {
              bid: wx.getStorageSync('bid'),
              type: 5
            },
            success: function (res) {

              if (res.code == 1) {
                app.request({
                  url: api.Coupon.getcoupon,
                  data: {
                    disid: res.data[0].disid,
                    uid: wx.getStorageSync('uid')
                  },
                  success: function (ress) {

                    if (ress.code == 1) {
                      wx.showModal({
                        title: '提示',
                        content: '恭喜你获得' + res.data[0].money + '元红包',
                        showCancel: false
                      })
                    }
                  }
                })
              }
            }
          })
        }
      }
    }
  },
  /**
   * 判断登录
   */
  isLogin: function () {
    // if (!wx.getStorageSync('phone')) {
    //   return false;
    // }
    // else {
    //   return true;
    // }
    return true;
  },
  gotoLogin: function () {
    wx.redirectTo({
      url: '/sd_liferuning/pages/login/index',
    })
  },
  
  /**
   * 获取用户信息并写入缓存
   */

  getUserInfo: function (e) {
   
    var that = this;
    var data = e.detail.rawData;
    console.log(data)
    if (data) {
      wx.showLoading({
        title: '请稍后',
        success:function(){
          console.log('ssss')
          wx.login({
            success: function (result) {
              wx.request({
                url: api.default.user,
                method: "POST",
                data: {
                  bid: wx.getStorageSync('bid'),
                  utoken: '',
                  code: result.code,
                  encryptedData: e.detail.encryptedData,
                  iv: e.detail.iv,
                },
                success: function (res) {
                  if (res.data.success == 10) {
                    wx.setStorageSync('openid', res.data.openid);
                    wx.request({
                      url: api.default.userid,
                      method: "POST",
                      data: {
                        openid: res.data.openid
                      },
                      success: function (ress) {
                        if (ress.data.data != '没有获取权限') {
                          wx.hideLoading();
                          wx.setStorageSync("uid", ress.data.data)
                          wx.setStorageSync("head", ress.data.head)
                          wx.setStorageSync("nickname", ress.data.nickname)
                          app.request({
                            url: api.default.login,
                            data: {
                              uid: ress.data.data,
                              bid: wx.getStorageSync('bid')
                            },
                            success: function (e) {
                              wx.setStorageSync('phone', e.phone);
                              wx.setStorageSync('cash', e.cash);
                              that.setData({
                                authStatus: true
                              });
                            }
                          })
                        } else {
                          wx.hideLoading();
                          wx.showModal({
                            title: '提示',
                            content: '请重新点击授权',
                            showCancel: false
                          })
                        }
                      },
                      fail:function(){
                        wx.hideLoading();
                        wx.showToast({
                          title: '网络错误',
                          icon:'none'
                        })
                      }
                    })
                  }else{
                    wx.hideLoading();
                    wx.showToast({
                      title: '服务器请求错误',
                      icon: 'none'
                    })
                  }
                },
                fail: function () {
                  wx.hideLoading();
                  wx.showToast({
                    title: '网络错误',
                    icon: 'none'
                  })
                }
              })
            }
          });
        }
      })
    }
  },
  closePanel: function () {
    this.setData({
      authStatus: true
    });
  },
  getLocaltion: function(){
    let _this = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        _this.setData({
          mapData: res
        });
      }
    })
  }
  
})

/**
 * 切换样式2的下标标记状态
 */
function scrollIconGroupAction({ page}) {
  setTimeout(function () {
    page.setData({
      currentScrollIcon: page.data.currentScrollIcon++ >= 3 ? 1 : page.data.currentScrollIcon
    })
    scrollIconGroupAction({ page: page });
  }, 3000)
}
function getAuthor() {
  wx.getLocation({
    type: 'wgs84',
    success: function (res) {
      var latitude = res.latitude
      var longitude = res.longitude
      var speed = res.speed
      var accuracy = res.accuracy
    }
  })
  wx.getSetting({
    success(res) {
      if (!res.authSetting['scope.userLocation']) {
        openSetting();
      }
    }
  })
}

function openSetting() {
  wx.openSetting({
    success: (res) => {
      if (!res.authSetting['scope.userLocation']) {
        showRemind();
      }
    }, fail: (res) => {
      if (!res.authSetting['scope.userLocation']) {
        showRemind();
      }
    }
  })
}

var timer; // 计时器
function dingshiqi() {
  timer = setTimeout(function () {
    // console.log('qqqqqqqqqqq');
    //判断会员是否过期
    app.request({
      url: api.member.viptime,
      data: {
        uid: wx.getStorageSync('uid')
      },
      success: function (e) {
        // console.log('eeeeee', e)
        if (e.data == '积分已经扣完'){
          clearTimeout(timer);
        }
      }
    })
    dingshiqi();
  },1000*60);
}
